package com.atzxh.guigu.netty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author 小红同学
 * @date 2023-12-12-21:53
 * @description     NIO群聊服务端
 */
public class GroupChatServer {

    // 定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    public static final int PORT = 6667;

    // 构造器 ==> 完成初始化工作
    public GroupChatServer() {
        try {
            // 获取 selector 和 ServerSocketChannel
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            // 绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置非阻塞
            listenChannel.configureBlocking(false);
            // 将 listenChannel 注册到 selector 中
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 监听
    public void listen() {
        try {
            while (true) {
                int count = selector.select();
                if (count > 0) {  // 有事件处理
                    // 遍历得到 SelectionKey 集合
                    Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                    while (keyIterator.hasNext()) {
                        // 取出 SelectionKey
                        SelectionKey key = keyIterator.next();

                        // 监听 accept
                        if (key.isAcceptable()) {
                            SocketChannel socketChannel = listenChannel.accept();
                            // 设置非阻塞
                            socketChannel.configureBlocking(false);
                            // 将该 socketChannel 注册到 selector
                            socketChannel.register(selector,SelectionKey.OP_READ);
                            // 提示用户上线
                            System.out.println(socketChannel.getRemoteAddress() + "已上线");
                        }

                        // 监听 read
                        if (key.isReadable()) {
                            readData(key);
                        }

                        // 手动移除当前的key
                        keyIterator.remove();
                    }
                } else {
                    System.out.println("等待中.......");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取客户端数据
    public void readData(SelectionKey key) {
        // key 相关联的 socketChannel
        SocketChannel socketChannel = null;

        try {
            // 得到 channel
            socketChannel = (SocketChannel) key.channel();
            // 创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            int count = socketChannel.read(buffer);
            if (count > 0) {
                String msg = new String(buffer.array());
                System.out.println("from 客户端 ==== " + msg);
                // 给其他客户端转发该消息
                forwardData(msg,socketChannel);
            }
        } catch (IOException e) {
            try {
                System.out.println(socketChannel.getRemoteAddress() + "已下线");
                // 取消注册
                key.cancel();
                // 关闭通道
                socketChannel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void forwardData(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中.....");
        for (SelectionKey key : selector.keys()) {
            Channel targetChannel = key.channel();
            // 排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                // 转型
                SocketChannel dest = (SocketChannel) targetChannel;
                // 将msg存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                // 将 buffer 中的数据写入通道
                dest.write(buffer);
            }
        }
    }
    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
